@model List<MVCWeekOne.Models.RoleDto>
@{
    ViewData["Title"] = "角色管理";
}

<style>
    /* 移除所有遮罩层 */
    .layui-layer-shade {
        display: none !important;
    }

    /* 确保弹窗可以正常交互 */
    .layui-layer {
        z-index: 9999 !important;
    }

    /* 确保弹窗内容可以正常点击 */
    .layui-layer-content {
        pointer-events: auto !important;
    }

    /* 移除任何可能的遮罩效果 */
    .layui-layer-shade,
    .layui-layer-shade[layui-layer-shade] {
        background: none !important;
        opacity: 0 !important;
        display: none !important;
    }

    /* 表格自适应样式 */
    .layui-card-body {
        padding: 15px;
        height: calc(100vh - 200px);
        overflow: hidden;
    }

    #roleTable {
        width: 100% !important;
    }

    .layui-table-view {
        height: 100% !important;
    }

    .layui-table-main {
        height: calc(100% - 40px) !important;
    }

    /* 确保表格容器铺满 */
    .layui-card {
        height: 100%;
        margin: 0;
    }
</style>

<div class="layui-card">
    <div class="layui-card-header">
        <div class="layui-row">
            <div class="layui-col-md6">
                <h3>角色管理</h3>
            </div>
            <div class="layui-col-md6" style="text-align: right;">
                <button class="layui-btn" id="addRoleBtn">添加角色</button>
            </div>
        </div>
    </div>
    <div class="layui-card-body">
        <!-- 查询条件 -->
        <form class="layui-form" id="searchForm">
            <div class="layui-row layui-col-space10">
                <div class="layui-col-md4">
                    <div class="layui-form-item">
                        <label class="layui-form-label">角色名称</label>
                        <div class="layui-input-block">
                            <input type="text" name="RoleName" placeholder="请输入角色名称" class="layui-input">
                        </div>
                    </div>
                </div>
                <div class="layui-col-md4">
                    <div class="layui-form-item">
                        <div class="layui-input-block">
                            <button class="layui-btn" lay-submit lay-filter="searchSubmit">查询</button>
                            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                        </div>
                    </div>
                </div>
            </div>
        </form>

        <!-- 角色列表 -->
        <table class="layui-table" id="roleTable" lay-filter="roleTable">

        </table>

        <!-- 分页 -->
        <div id="rolePager"></div>
    </div>
</div>

<!-- 状态模板 -->
<script type="text/html" id="stateTpl">
    {{# if(d.isState) { }}
        <span class="layui-badge layui-bg-green">启用</span>
    {{# } else { }}
        <span class="layui-badge layui-bg-gray">禁用</span>
    {{# } }}
</script>

<!-- 权限模板 -->
<script type="text/html" id="permissionTpl">
    {{# if(d.permissionNames && d.permissionNames.length > 0) { }}
        {{d.permissionNames.join(', ')}}
    {{# } else { }}
        <span class="layui-text-gray">无权限</span>
    {{# } }}
</script>

<!-- 操作模板 -->
<script type="text/html" id="operationTpl">
    <button class="layui-btn layui-btn-xs" lay-event="edit">编辑</button>
    <button class="layui-btn layui-btn-xs layui-btn-danger" lay-event="delete">删除</button>
</script>

<!-- 添加角色弹窗 -->
<div id="addRoleModal" style="display: none; padding: 20px;">
    <form class="layui-form" id="addRoleForm">
        <div class="layui-form-item">
            <label class="layui-form-label">角色名称</label>
            <div class="layui-input-block">
                <input type="text" name="RoleName" required lay-verify="required" placeholder="请输入角色名称"
                    class="layui-input">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">权限</label>
            <div class="layui-input-block" id="permissionCheckboxes">
                <!-- 权限复选框将在这里动态生成 -->
            </div>
        </div>

        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn" lay-submit lay-filter="addRoleSubmit">提交</button>
                <button type="button" class="layui-btn layui-btn-primary" id="resetRoleBtn">重置</button>
            </div>
        </div>
    </form>
</div>

<!-- 编辑角色弹窗 -->
<div id="editRoleModal" style="display: none; padding: 20px;">
    <form class="layui-form" id="editRoleForm">
        <input type="hidden" name="Id" id="editRoleId">
        <div class="layui-form-item">
            <label class="layui-form-label">角色名称</label>
            <div class="layui-input-block">
                <input type="text" name="RoleName" required lay-verify="required" placeholder="请输入角色名称"
                    class="layui-input">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">权限</label>
            <div class="layui-input-block" id="editPermissionCheckboxes">
                <!-- 权限复选框将在这里动态生成 -->
            </div>
        </div>

        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn" lay-submit lay-filter="editRoleSubmit">更新</button>
                <button type="button" class="layui-btn layui-btn-primary" id="editResetBtn">重置</button>
            </div>
        </div>
    </form>
</div>

@section Scripts {
    <script>
        layui.use(['table', 'form', 'layer', 'laypage'], function () {
            var table = layui.table;
            var form = layui.form;
            var layer = layui.layer;
            var laypage = layui.laypage;


            // 初始化角色表格
            initRoleTable(table, layer);

            // 查询表单提交
            form.on('submit(searchSubmit)', function (data) {
                loadRoleData(1, data.field, table);
                return false;
            });

            // 加载权限数据
            loadPermissions().catch(function (error) {
                console.error('初始化权限数据失败:', error);
            });



            // 添加角色按钮点击事件
            $('#addRoleBtn').click(function () {
                // 先加载权限数据，然后打开弹窗
                loadPermissions().then(function () {
                    layui.layer.open({
                        type: 1,
                        title: '添加角色',
                        area: ['600px', '500px'],
                        content: $('#addRoleModal'),
                        shade: false, // 移除遮罩层
                        shadeClose: false,
                        maxmin: false,
                        closeBtn: 1,
                        success: function (layero, index) {
                            // 弹窗打开后重新渲染表单
                            layui.form.render();


                            // 确保弹窗内容可以交互
                            $(layero).find('input, select, button').prop('disabled', false);

                            // 阻止事件冒泡
                            $(layero).on('click', function (e) {
                                e.stopPropagation();
                            });

                            // 聚焦到第一个输入框
                            setTimeout(function () {
                                $('#addRoleForm input[name="RoleName"]').focus();
                            }, 100);

                            // 绑定重置按钮事件
                            $(layero).find('#resetRoleBtn').on('click', function (e) {
                                e.preventDefault();
                                e.stopPropagation();
                                $('#addRoleForm')[0].reset(); // 清空表单
                                $('#permissionCheckboxes input:checked').prop('checked', false); // 清空权限选择
                                layui.form.render(); // 重新渲染表单
                                layui.layer.msg('表单已重置', { icon: 1 });
                            });

                            // 直接绑定提交按钮事件
                            $(layero).find('button[lay-submit][lay-filter="addRoleSubmit"]').on('click', function (e) {
                                e.preventDefault();
                                e.stopPropagation();
                                console.log('提交按钮被点击');
                                handleAddRoleSubmit();
                            });
                        },
                        end: function () {
                            // 弹窗关闭后清空表单
                            $('#addRoleForm')[0].reset();
                            layui.form.render();
                        }
                    });
                }).catch(function (error) {
                    layui.layer.msg('加载权限数据失败: ' + error, { icon: 2 });
                });
            });

            // 添加角色表单提交处理函数
            function handleAddRoleSubmit() {
                console.log('处理添加角色提交');

                // 获取表单数据
                var roleName = $('#addRoleForm input[name="RoleName"]').val();
                console.log('角色名称:', roleName);

                if (!roleName) {
                    layui.layer.msg('请输入角色名称', { icon: 2 });
                    return;
                }

                // 获取选中的权限并转换为数字
                var selectedPermissions = [];
                $('#permissionCheckboxes input:checked').each(function () {
                    selectedPermissions.push(parseInt($(this).val()));
                });
                console.log('选中的权限:', selectedPermissions);

                var postData = {
                    RoleName: roleName,
                    PermissionIds: selectedPermissions
                };

                console.log('提交的数据:', postData);

                var loadIndex = layui.layer.load(1, {
                    shade: [0.1, '#fff']
                });

                $.ajax({
                    url: '@Url.Action("AddRole", "Role")',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(postData),
                    success: function (res) {
                        layui.layer.close(loadIndex);
                        console.log('服务器响应:', res);
                        if (res.success) {
                            layui.layer.msg(res.message, { icon: 1 });
                            layui.layer.closeAll();
                            layui.table.reload('roleTable');
                        } else {
                            layui.layer.msg(res.message, { icon: 2 });
                        }
                    },
                    error: function (xhr, status, error) {
                        layui.layer.close(loadIndex);
                        console.error('AJAX错误:', xhr.responseText);
                        console.error('状态码:', xhr.status);
                        console.error('错误信息:', error);
                        layui.layer.msg('操作失败', { icon: 2 });
                    }
                });
            }


        });

        // 初始化角色表格
        function initRoleTable(table, layer) {

            table.render({
                elem: '#roleTable',
                url: '@Url.Action("GetRolePage", "Role")',
                method: 'get',
                where: getSearchParams(),
                page: true,
                limit: 10,
                limits: [10, 20, 50, 100],
                cols: [[
                    { type: 'numbers', title: '序号', width: 80, fixed: 'left' },
                    { field: 'roleName', title: '角色名称', minWidth: 120 },
                    { field: 'permissionNames', title: '权限', minWidth: 200, templet: '#permissionTpl' },
                    { field: 'isState', title: '状态', width: 100, templet: '#stateTpl' },
                    {
                        field: 'createTime', title: '创建时间', minWidth: 160, sort: true, templet: function (d) {
                            if (!d.createTime) return '';
                            var date = new Date(d.createTime);
                            var year = date.getFullYear();
                            var month = String(date.getMonth() + 1).padStart(2, '0');
                            var day = String(date.getDate()).padStart(2, '0');
                            var hours = String(date.getHours()).padStart(2, '0');
                            var minutes = String(date.getMinutes()).padStart(2, '0');
                            var seconds = String(date.getSeconds()).padStart(2, '0');
                            return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;
                        }
                    },
                    { field: 'operation', title: '操作', width: 200, templet: '#operationTpl', fixed: 'right' }
                ]],
                parseData: function (res) {
                    return {
                        "code": res.code,
                        "msg": res.msg,
                        "count": res.count,
                        "data": res.data
                    };
                },
                done: function (res, curr, count) {
                    if (res.code !== 0) {
                        layui.layer.msg('获取数据失败: ' + res.msg, { icon: 2 });
                    }
                },
                error: function (res) {
                    layui.layer.msg('表格加载失败', { icon: 2 });
                }
            });

            // 监听工具条事件
            table.on('tool(roleTable)', function (obj) {
                var data = obj.data;
                if (obj.event === 'edit') {
                    editRole(data.id);
                } else if (obj.event === 'delete') {
                    deleteRole(data.id);
                }
            });
        }

        // 获取查询参数
        function getSearchParams() {
            var params = {};
            $('#searchForm').serializeArray().forEach(function (item) {
                if (item.value) {
                    params[item.name] = item.value;
                }
            });
            return params;
        }

        // 加载角色数据
        function loadRoleData(page, params, table) {

            table.reload('roleTable', {
                where: params,
                page: {
                    curr: page
                }
            });
        }

        // 全局函数：加载权限数据
        function loadPermissions() {
            return new Promise(function (resolve, reject) {
                console.log('开始加载权限数据...');
                $.ajax({
                    url: '@Url.Action("GetPermissions", "Role")',
                    type: 'GET',
                    success: function (res) {
                        console.log('权限数据响应:', res);
                        if (res.success) {
                            window.permissions = res.data;
                            console.log('权限数据:', res.data);

                            renderPermissionCheckboxes('#permissionCheckboxes');
                            resolve();
                        } else {
                            console.error('权限数据加载失败:', res.message);
                            reject('权限数据加载失败: ' + res.message);
                        }
                    },
                    error: function (xhr, status, error) {
                        console.error('权限数据加载错误:', xhr.responseText);
                        reject('权限数据加载失败');
                    }
                });
            });
        }

        // 全局函数：渲染权限复选框
        function renderPermissionCheckboxes(containerId, selectedIds) {
            var container = $(containerId);
            container.empty();

            if (window.permissions) {
                window.permissions.forEach(function (permission) {
                    var checked = selectedIds && selectedIds.includes(permission.id) ? 'checked' : '';
                    container.append(`
                                        <input type="checkbox" name="permissions" value="${permission.id}" title="${permission.permissionName}" ${checked}>
                                    `);
                });

                layui.form.render('checkbox');
            }
        }

        // 全局函数：编辑角色
        function editRole(roleId) {
            console.log('编辑角色ID:', roleId);

            // 先加载角色数据
            $.ajax({
                url: '@Url.Action("GetRoleById", "Role")',
                type: 'GET',
                data: { roleId: roleId },
                success: function (res) {
                    if (res.success) {
                        openEditRoleModal(res.data);
                    } else {
                        layui.layer.msg(res.message || '获取角色信息失败', { icon: 2 });
                    }
                },
                error: function (xhr, status, error) {
                    console.error('获取角色信息失败:', xhr.responseText);
                    layui.layer.msg('获取角色信息失败', { icon: 2 });
                }
            });
        }

        // 打开编辑角色弹窗
        function openEditRoleModal(roleData) {
            // 先加载权限数据，然后打开弹窗
            loadPermissions().then(function () {
                layui.layer.open({
                    type: 1,
                    title: '编辑角色',
                    area: ['600px', '500px'],
                    content: $('#editRoleModal'),
                    shade: false,
                    shadeClose: false,
                    maxmin: false,
                    closeBtn: 1,
                    success: function (layero, index) {
                        layui.form.render();

                        // 填充表单数据
                        $('#editRoleId').val(roleData.id);
                        $('#editRoleForm input[name="RoleName"]').val(roleData.roleName);

                        // 设置权限选择
                        renderPermissionCheckboxes('#editPermissionCheckboxes', roleData.permissionIds);

                        // 确保弹窗内容可以交互
                        $(layero).find('input, select, button').prop('disabled', false);

                        // 阻止事件冒泡
                        $(layero).on('click', function (e) {
                            e.stopPropagation();
                        });

                        // 绑定更新按钮事件
                        $(layero).find('button[lay-submit][lay-filter="editRoleSubmit"]').on('click', function (e) {
                            e.preventDefault();
                            e.stopPropagation();
                            handleEditRoleSubmit();
                        });

                        // 绑定重置按钮事件
                        $(layero).find('#editResetBtn').on('click', function (e) {
                            e.preventDefault();
                            e.stopPropagation();
                            $('#editRoleForm input[name="RoleName"]').val(roleData.roleName);
                            renderPermissionCheckboxes('#editPermissionCheckboxes', roleData.permissionIds);
                            layui.form.render();
                            layui.layer.msg('表单已重置', { icon: 1 });
                        });
                    },
                    end: function () {
                        $('#editRoleModal').hide();
                    }
                });
            }).catch(function (error) {
                layui.layer.msg('加载权限数据失败: ' + error, { icon: 2 });
            });
        }

        // 编辑角色提交处理函数
        function handleEditRoleSubmit() {
            console.log('处理编辑角色提交');

            var roleId = $('#editRoleId').val();
            var roleName = $('#editRoleForm input[name="RoleName"]').val();

            console.log('角色ID:', roleId, '类型:', typeof roleId);
            console.log('角色名称:', roleName, '类型:', typeof roleName);

            if (!roleName) {
                layui.layer.msg('请输入角色名称', { icon: 2 });
                return;
            }

            // 获取选中的权限并转换为数字
            var selectedPermissions = [];
            $('#editPermissionCheckboxes input:checked').each(function () {
                selectedPermissions.push(parseInt($(this).val()));
            });

            var postData = {
                RoleId: parseInt(roleId),
                RoleName: roleName,
                PermissionIds: selectedPermissions
            };

            console.log('提交的编辑数据:', postData);
            console.log('JSON字符串:', JSON.stringify(postData));

            var loadIndex = layui.layer.load(1, {
                shade: [0.1, '#fff']
            });

            $.ajax({
                url: '@Url.Action("UpdateRole", "Role")',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(postData),
                success: function (res) {
                    layui.layer.close(loadIndex);
                    console.log('服务器响应:', res);
                    if (res.success) {
                        layui.layer.msg(res.message, { icon: 1 });
                        layui.layer.closeAll();
                        layui.table.reload('roleTable');
                    } else {
                        layui.layer.msg(res.message, { icon: 2 });
                    }
                },
                error: function (xhr, status, error) {
                    layui.layer.close(loadIndex);
                    console.error('AJAX错误:', xhr.responseText);
                    layui.layer.msg('操作失败', { icon: 2 });
                }
            });
        }

        // 删除角色
        function deleteRole(roleId) {
            layui.layer.confirm('确定要删除这个角色吗？', {
                shade: false,
                shadeClose: false,
                title: '确认删除'
            }, function (index) {
                layui.layer.close(index);

                var loadIndex = layui.layer.load(1, {
                    shade: [0.1, '#fff']
                });

                $.ajax({
                    url: '@Url.Action("DeleteRole", "Role")',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify({ roleId: parseInt(roleId) }),
                    success: function (res) {
                        layui.layer.close(loadIndex);
                        if (res.success) {
                            layui.layer.msg(res.message, { icon: 1 });
                            layui.table.reload('roleTable');
                        } else {
                            layui.layer.msg(res.message, { icon: 2 });
                        }
                    },
                    error: function (xhr, status, error) {
                        layui.layer.close(loadIndex);
                        console.error('删除失败:', xhr.responseText);
                        layui.layer.msg('删除失败', { icon: 2 });
                    }
                });
            });
        }

        // 全局函数：移除所有遮罩层
        function removeAllShades() {
            // 移除所有遮罩层
            $('.layui-layer-shade').remove();
            $('[layui-layer-shade]').remove();
            $('.layui-layer-shade[layui-layer-shade]').remove();

            // 移除任何可能的遮罩元素
            $('body').find('[class*="shade"]').remove();
            $('body').find('[class*="mask"]').remove();

        }

        // 定期检查并移除遮罩层
        function startShadeRemoval() {
            setInterval(function () {
                removeAllShades();
            }, 100); // 每100ms检查一次
        }

        // 页面加载完成后初始化
        $(document).ready(function () {

            // 移除所有遮罩层
            removeAllShades();
            // 定期检查并移除遮罩层
            startShadeRemoval();

            // 添加快捷键支持
            $(document).keydown(function (e) {
                // ESC键关闭所有弹窗
                if (e.keyCode === 27) {
                    layui.layer.closeAll();
                }
            });
        });
    </script>
}
